<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/meow.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/meow.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/blue/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"meowxue.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="在Java中有很多动态代理技术，比如JDK、CGLIB、Javassist、ASM，其中最常用的动态代理技术有两种：一种是JDK动态代理，这是JDK自带的功能；另一种是CGLIB，这是第三方提供的一个技术。目前，Spring常用JDK和CGLIB，而MyBatis还使用了Javassist，无论哪种代理其技术，它们的理念都是相似的。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java动态代理">
<meta property="og:url" content="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/index.html">
<meta property="og:site_name" content="喵小哥儿の博客">
<meta property="og:description" content="在Java中有很多动态代理技术，比如JDK、CGLIB、Javassist、ASM，其中最常用的动态代理技术有两种：一种是JDK动态代理，这是JDK自带的功能；另一种是CGLIB，这是第三方提供的一个技术。目前，Spring常用JDK和CGLIB，而MyBatis还使用了Javassist，无论哪种代理其技术，它们的理念都是相似的。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-03-11T06:45:00.000Z">
<meta property="article:modified_time" content="2024-03-15T04:00:25.251Z">
<meta property="article:author" content="喵小哥儿">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/","path":"2024/03/11/技能/java/动态代理/","title":"Java动态代理"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java动态代理 | 喵小哥儿の博客</title>
  







<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.css"><style>
#needsharebutton-postbottom {
  cursor: pointer;
  height: 26px;
  margin-top: 10px;
  position: relative;
}
#needsharebutton-postbottom .btn {
  border: 1px solid $btn-default-border-color;
  border-radius: 3px;
  display: initial;
  padding: 1px 4px;
}
</style>
  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">喵小哥儿の博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-shuoshuo"><a href="/shuoshuo/" rel="section"><i class="fa fa-comment fa-fw"></i>碎念</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-1-JDK%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-number">1.</span> <span class="nav-text">1.1 JDK动态代理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-2-CGLIB-%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">1.2 CGLIB 动态代理</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="喵小哥儿"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">喵小哥儿</p>
  <div class="site-description" itemprop="description">慢热，沉默，抽烟，小酌，喜欢独处，半点斯文，半点猥琐。</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="mailto:meowxue@163.com" title="E-Mail → mailto:meowxue@163.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i></a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="喵小哥儿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="喵小哥儿の博客">
      <meta itemprop="description" content="慢热，沉默，抽烟，小酌，喜欢独处，半点斯文，半点猥琐。">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java动态代理 | 喵小哥儿の博客">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java动态代理
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2024-03-11 14:45:00" itemprop="dateCreated datePublished" datetime="2024-03-11T14:45:00+08:00">2024-03-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%8A%80%E8%83%BD/" itemprop="url" rel="index"><span itemprop="name">技能</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>1.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

          
          
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>在Java中有很多动态代理技术，比如JDK、CGLIB、Javassist、ASM，其中最常用的动态代理技术有两种：一种是JDK动态代理，这是JDK自带的功能；另一种是CGLIB，这是第三方提供的一个技术。目前，Spring常用JDK和CGLIB，而MyBatis还使用了Javassist，无论哪种代理其技术，它们的理念都是相似的。</p>
<span id="more"></span>

<h1 id="1-1-JDK动态代理"><a href="#1-1-JDK动态代理" class="headerlink" title="1.1 JDK动态代理"></a>1.1 JDK动态代理</h1><p>JDK动态代理是java.lang.reflect.* 包提供的方式，它必须借助一个接口才能产生代理对象，所以先定义接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> interfact HelloWorld &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayHelloWorld</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后提供实现类HelloWorldImpl 来实现接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> HelloWorldImpl <span class="keyword">implements</span> <span class="title class_">HelloWorld</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayHelloWorld</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;Hello World&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这时最简单的Java接口和实现类的关系，此时可以开始动态代理了。按照我们之前的分析，先要建立起代理对象和真实服务对象的关系，然后实现代理逻辑，所以一共分为两个步骤。</p>
<p>在JDK动态代理中，要实现代理逻辑类必须去实现java.lang.reflect.InvocationHandler接口，它里面定义了一个 invoke 方法，并提供接口数组用于下挂代理对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JdkProxyExample</span> <span class="keyword">implements</span> <span class="title class_">InvocationHandler</span> &#123;</span><br><span class="line">    <span class="comment">//真实对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">Object</span> <span class="variable">target</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 建立代理对象和真实对象的代理关系，并返回代理对象</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> target 真实对象</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> 代理对象</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">bind</span><span class="params">(Object target)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.target = target;</span><br><span class="line">        <span class="keyword">return</span> Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), <span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 代理方法逻辑</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> proxy 代理对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> method 当前调度方法</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> args 当前方法参数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 代理结果返回</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Throwable 异常</span></span><br><span class="line"><span class="comment">     */</span>    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;进入代理逻辑方法&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;在调度真实对象之前的服务&quot;</span>);</span><br><span class="line">        <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> method.invoke(target, args);<span class="comment">//相当于调用sayHelloWorld方法</span></span><br><span class="line">        System.out.println(<span class="string">&quot;在调度真实对象之后的服务&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> obj;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第1步，建立代理对象和真实对象的关系。这里是使用了bind方法去完成的，方法里面首先用类的属性target保存了真实对象，然后通过下面的代码建立并生成代理对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), <span class="built_in">this</span>);</span><br></pre></td></tr></table></figure>

<p>其中newProxyInstance方法包含三个参数。</p>
<ul>
<li>第一个是类加载器，我们才有了target本身的类加载器。</li>
<li>第二个是把生成的动态代理对象下挂在哪些接口下，这个写法就是放在target实现的接口下。HelloWorldImpl对象的接口显然就是HelloWorld，代理对象可以这样声明：HelloWorld proxy &#x3D; xxxx;。</li>
<li>第三个是定义实现方法逻辑的代理类，this表示当前对象，它必须实现InvocationHandler接口的invoke方法，它就是代理逻辑方法的现实方法。</li>
</ul>
<p>第2步，实现代理逻辑方法。invoke方法可以实现代理逻辑，invoke方法的3个参数的含义如下：</p>
<ul>
<li>proxy，代理对象，就是build方法生成的对象。</li>
<li>method，当前调度的调度方法</li>
<li>args，调度方法的参数</li>
<li>当我们使用了代理对象调度方法后，它就会进入到invoke方法里面。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> method.invoke(target, args);</span><br></pre></td></tr></table></figure>

<p>这行代码相当于调度真实对象的方法，只是通过反射实现而已。<br>类比前面的例子，proxy相当于商务对象，target相当于软件工程师对象，bind方法就是建立商务和软件工程师代理关系的方法。而invoke就是商务逻辑，它将控制软件工程师的访问。</p>
<p>测试JDK动态代理：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testJdkProxy</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">JdkProxyExample</span> <span class="variable">jdk</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JdkProxyExample</span>();</span><br><span class="line">    <span class="comment">//绑定关系，因为挂在接口 HelloWorld 下，所以声明代理对象 HelloWorld proxy</span></span><br><span class="line">    <span class="type">HelloWorld</span> <span class="variable">proxy</span> <span class="operator">=</span> (HelloWorld)jdk.bind(<span class="keyword">new</span> <span class="title class_">HelloWorldImpl</span>());</span><br><span class="line">    proxy.sayHelloWorld();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先通过bind方法绑定了代理关系，然后在代理对象调度sayHelloWorld方法时进入了代理的逻辑，测试结果如下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">进入代理逻辑方法</span><br><span class="line">在调度真实对象之前的服务</span><br><span class="line">Hello World</span><br><span class="line">在调度真实对象之后的服务</span><br></pre></td></tr></table></figure>

<p>此时，在调度打印Hello World 之前和之后都可以嫁入相关的逻辑，甚至可以不调度Hello World的打印。</p>
<p>这就是JDK动态代理，它是一种常用的动态代理，十分重要，后面会以JDK动态代理为主讨论框架的实现。</p>
<h1 id="1-2-CGLIB-动态代理"><a href="#1-2-CGLIB-动态代理" class="headerlink" title="1.2 CGLIB 动态代理"></a>1.2 CGLIB 动态代理</h1><p>Jdk动态代理必须提供接口才能使用，在一些不能提供接口的环境中，只能采用其他第三方技术，比如CGLIB动态代理，它的优势在于不需要提供接口，只要一个非抽象类就能实现动态代理。</p>
<p>下面的ReflectServiceImpl 类作为例子，它不存在实现任何接口，所以没办法使用JDK动态代理，这里采用CGLIB动态代理技术</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CglibProxyExample</span> <span class="keyword">implements</span> <span class="title class_">MethodInterceptor</span> &#123;  </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生成CGLIB代理对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cls —— Class对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> Class 类的CGLIB代理对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">getProxy</span><span class="params">(Class cls)</span> &#123;</span><br><span class="line">        <span class="comment">//CGLIB enhancer 增强类对象</span></span><br><span class="line">        <span class="type">Enhancer</span> <span class="variable">enhancer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Enhancer</span>();</span><br><span class="line">        <span class="comment">//设置增强类型</span></span><br><span class="line">        enhancer.setSuperclass(cls);</span><br><span class="line">        <span class="comment">//定义代理逻辑对象为当前对象，要求当前对象实现MethodInterceptor方法</span></span><br><span class="line">        enhancer.setCallback(<span class="built_in">this</span>);</span><br><span class="line">        <span class="comment">//生成并返回代理对象</span></span><br><span class="line">        <span class="keyword">return</span> enhancer.create();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 代理逻辑方法</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> proxy 代理对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> method 方法</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> args 方法参数</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> methodProxy 方法代理</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 代理逻辑返回</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> Throwable 异常</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> Object <span class="title function_">intercept</span><span class="params">(Object proxy, Method method, Object[] args, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">		System.err.println(<span class="string">&quot;调用真实对象前&quot;</span>);</span><br><span class="line">		<span class="comment">//CGLIB反射调用真实对象</span></span><br><span class="line">		<span class="type">Object</span> <span class="variable">result</span> <span class="operator">=</span> methodProxy.invokeSuper(proxy, args);</span><br><span class="line">		System.err.println(<span class="string">&quot;调用真实对象后&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里调用了CGLIB的加强者Enhancer，通过设置超类的方法（setSuperclass），然后通过setCallback方法设置哪个类为它的代理类。其中，参数为this就意味着是当前对象，那就要求用this这个对象实现接口MethodInterceptor的方法——intercept，然后返回代理对象。</p>
<p>那么此时当前类的intercept方法就是其代理逻辑方法，其参数内容见代码注解，我们在反射真实对象方法前后进行了打印，CGLIB是通过如下代码完成的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Object</span> <span class="variable">result</span> <span class="operator">=</span> methodProxy.invokeSuper(proxy, args);</span><br></pre></td></tr></table></figure>

<p>下面是测试CGLIB动态代理的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">    <span class="type">CglibProxyExample</span> <span class="variable">cpe</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">CglibProxyExample</span>();</span><br><span class="line">    <span class="type">ReflectServiceImpl</span> <span class="variable">obj</span> <span class="operator">=</span> (ReflectServiceImpl) cpe.getProxy(ReflectServiceImpl.class);</span><br><span class="line">    obj.sayHello(<span class="string">&quot;张三&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用结果：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">调用真实对象前</span><br><span class="line">Hello 张三</span><br><span class="line">调用真实对象后</span><br></pre></td></tr></table></figure>

<p>掌握了JDK动态代理就很容易掌握CGLIB动态代理，因为二者是相似的。它们都是用getProxy方法生成代理对象，制定代理的逻辑类。而代理逻辑类要实现一个接口的一个方法，那么这个接口定义的方法就是代理对象的逻辑方法，它可以控制真实对象的方法。</p>

    </div>

    
    
    

    <footer class="post-footer"><div class="post-widgets">
      <div id="needsharebutton-postbottom">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    </div>
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>喵小哥儿
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/" title="Java动态代理">https://meowxue.gitee.io/2024/03/11/技能/java/动态代理/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/" rel="prev" title="Java反射技术">
                  <i class="fa fa-angle-left"></i> Java反射技术
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2024/03/18/%E9%80%9F%E6%9F%A5/%E7%94%B5%E8%84%91%E6%9C%AC%E5%9C%B0%E6%96%87%E4%BB%B6%E6%8E%A8%E9%80%81%E5%88%B0git/" rel="next" title="将电脑本地文件推送到git">
                  将电脑本地文件推送到git <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">喵小哥儿</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">25k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:29</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  <script src="/js/third-party/pace.js"></script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.js"></script>
  <script>
      pbOptions = {};
        pbOptions.iconStyle = "box";
        pbOptions.boxForm = "horizontal";
        pbOptions.position = "bottomCenter";
        pbOptions.networks = "Wechat,QQZone,Weibo,Douban,Twitter,Facebook";
      new needShareButton('#needsharebutton-postbottom', pbOptions);
  </script>
</body>
</html>
